# -*- coding: utf-8 -*-

"""
Description: 喀斯玛工具
"""

import json
from bs4 import BeautifulSoup
import re


def del_prolist_attrs(data_lsit):
    """删除商品列表无用属性

    Args:
        data_lsit (_type_): 卖家商品店铺列表

    Returns:
        _type_: _description_
    """

    # 只保留价格和货号
    # only_price = [
    #     "brandAgent",
    #     "brandName",
    #     "canOnline",
    #     "dangerMsds",
    #     "dangerousCateName",
    #     "isPromotion",
    #     "proCasNo",
    #     "proCateId",
    #     "proDeliveryCycle",
    #     "proId",
    #     "proImg",
    #     "proMktPrice",
    #     "proName",
    #     "proSpec",
    #     "proTags",
    #     "proUnit",
    #     "promotionPrice",
    #     "settlementStatus",
    #     "supplier",
    #     "supplierId",
    #     "yqjCate",
    # ]
    del_keys = [
        "brandAgent",
        "proTags",
        "canOnline",
        "dangerMsds",
        "supplier",
        "yqjCate",
        "dangerousCateName",
        "settlementStatus",
        "isPromotion",
    ]

    for item in data_lsit:
        for key in del_keys:
            item.pop(key, None)  # 不存在也不会报错
    return data_lsit


def combine_dict(prolist) -> dict:

    return "123"


def line_to_dict(file_name) -> dict:
    """将单行 dict转化为大 dict

    Args:
        file_name (_type_): 文件名称

    Returns:
        dict: _description_
    """
    # 4121
    _dict = {}
    with open(file_name, "r", encoding="utf-8") as f:
        while True:
            line = f.readline()
            if not line:
                break
            _dict.update(json.loads(line))

    return _dict


def extract_delivery_date(script_text: str) -> str:
    """从JavaScript代码中提取货期值"""
    pattern = r"var\s+date_val\s*=\s*'(\d+)'"
    match = re.search(pattern, script_text)
    if match:
        return match.group(1)
    return ""


def extract_search_details(html_content: str) -> list[dict]:
    """
    提取搜索页商品信息

    Args:
        html_content (str): 包含商品信息的HTML内容

    Returns:
        list: 包含商品详细信息的列表，每个商品信息为一个字典，包含以下字段：
            - base_url: 商品基础URL
            - product_id: 商品ID
            - sku_id: SKU ID
            - product_name: 商品名称
            - current_price: 当前价格
            - original_price: 原价
            - specs: 商品规格信息字典，包含货号、规格、货期等
            - supplier: 供应商信息
    """
    # 使用BeautifulSoup解析HTML
    soup = BeautifulSoup(html_content, "html.parser")

    # 查找所有包含productDetailsFn的div元素
    # product_divs = soup.find_all("div", {"class": "cas_blk02 cas_blk02_bg"})
    product_divs = soup.find_all("div", {"class": "cas_blk02"})

    products_info = []

    for product_div in product_divs:
        # 获取onclick属性
        onclick_attr = product_div.get("onclick", "")

        # 使用正则表达式提取参数
        pattern = r"productDetailsFn\('([^']*)','([^']*)','([^']*)',\s*(\d+)\)"
        match = re.search(pattern, onclick_attr)

        if match:
            base_url, supplier_id, product_id, param = match.groups()

            # 提取商品名称
            product_name = product_div.find("div", {"class": "pro-name"}).text.strip()

            # 提取价格信息
            price_div = product_div.find("div", {"class": "cas_b02_info04"})
            current_price = price_div.find("strong").text.strip().replace("¥", "")
            original_price = price_div.find("i").text.strip().replace("¥", "")

            # 提取商品规格信息
            specs = {}
            spec_divs = product_div.find_all("p", {"class": "one-line"})
            for spec in spec_divs:
                text = spec.text.strip()
                if "：" in text:
                    key, value = text.split("：", 1)
                    specs[key] = value.strip()

                    # 如果是货期，尝试从JavaScript中获取实际值
                    if key == "货期":
                        script_tag = spec.find_next("script")
                        if script_tag:
                            delivery_date = extract_delivery_date(script_tag.string)
                            if delivery_date:
                                specs[key] = f"{delivery_date}天"

            # 提取供应商信息
            supplier_div = product_div.find(
                "div",
                {"class": "cas_b02_info06", "style": "width: 180px;margin-left: 10px;"},
            )
            supplier_name = supplier_div.find("a").get("title", "")
            supplier_url = supplier_div.find("a").get("href", "")

            # 提取商品图片URL
            img_tag = product_div.find("img", {"id": re.compile(r"^proImg\d+$")})
            img_url = img_tag.get("src", "") if img_tag else ""

            product_info = {
                "base_url": base_url,
                "supplier_id": supplier_id,
                "product_id": product_id,
                "product_detail_url": f"{base_url}/product-details/page/{supplier_id}/{product_id}",
                "param": param,
                "product_name": product_name,
                "current_price": current_price,
                "original_price": original_price,
                "specifications": specs,
                "supplier_name": supplier_name,
                "supplier_url": supplier_url,
                "image_url": img_url,
            }

            products_info.append(product_info)

    return products_info


def extract_product_details(html_content: str) -> dict:
    """
    提取商品详情页信息

    Args:
        html_content (str): 包含商品详情的HTML内容

    Returns:
        dict: 包含商品详细信息的字典，包含以下字段：
            - product_name: 商品名称
            - product_detail_str: 商品详情字符串
    """

    variables = [
        'productCode',
        'productSpec',
        'productUnit',
        'cateName',
        'proPrice'
    ]
    
    # 创建结果字典
    re_result = {}
    
    # 需要保留两位小数的字段
    price_fields = ['proPrice']
    
    # 使用正则表达式提取每个变量的值
    for var in variables:
        # 匹配 var 或 let 声明的变量
        pattern = f"(?:var|let) {var} = ['\"](.*?)['\"]"
        match = re.search(pattern, html_content)
        if match:
            value = match.group(1)
            if var in price_fields:
                try:
                    value = f"{float(value):.2f}"
                except Exception:
                    pass
            re_result[var] = value
        else:
            re_result[var] = None

    soup = BeautifulSoup(html_content, 'html.parser')
    
    # 初始化商品信息字典
    product_info = {}

    product_name = soup.find("title").text.strip()
    # 商品基础信息
    product_info_div = soup.find("div", {"class": "cas_b14_info01"})
    font_list = product_info_div.find_all("font")

    product_info["name"] = product_name
    product_info["code"] = font_list[0].text.strip()
    product_info["cas"] = font_list[1].text.strip()
    product_info["specs"] = font_list[2].text.strip()
    product_info["delivery_date"] = font_list[3].text.strip()

    # 商品详情
    prodes_div = soup.find("div", {"class": "cas_b15_main ke-content"})
    product_detail_str = str(prodes_div.find("body"))
   

    product_info["price"] = re_result["proPrice"]
    product_info["specs"] = re_result["productSpec"]+'/'+re_result["productUnit"]
    product_info["category"] = re_result["cateName"]
    product_info["code"] = re_result["productCode"]
    product_info["description"] = product_detail_str
    
    product_attributes = {}
    if prodes_div:
        attribute_table = prodes_div.find('table')
        if attribute_table:
            for row in attribute_table.find_all('tr'):
                for cell in row.find_all('td'):
                    span = cell.find('span')
                    if span and 'title' in span.attrs:
                        title = span['title']
                        if '：' in title:
                            key, value = title.split('：', 1)
                            key = key.strip()
                            if key != '退换货说明':
                                product_attributes[key] = value.strip()
    
    product_info['product_attributes'] = product_attributes
    return product_info